<script setup>
/*----------------------* 封禁用户管理页面 *----------------------*/

import {onMounted, ref, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import http from "@/request/http.js";
import {useRoute} from "vue-router";

const route = useRoute();

// 封禁用户列表数据
const banUserList = ref([]);

// 选中的封禁记录ID数组
const selectedBanIds = ref([]);

// 搜索表单数据
const searchForm = ref({
  userId: '',        // 用户ID
  userBanType: ''    // 封禁类型
});

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0
});

// 解封相关变量
const unbanDialog = ref(false);
const unbanForm = ref({
  banIds: [],        // 选中的封禁记录ID
  unbanReason: ''    // 解封原因
});

// 处理多选框选择事件
const handleSelectionChange = (selection) => {
  selectedBanIds.value = selection.map(item => item.ubanId);
};

// 搜索方法：加载封禁用户列表
const handleSearch = async () => {
  try {
    const params = {
      currentPage: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      userId: searchForm.value.userId,
      userBanType: searchForm.value.userBanType
    };

    // 移除空参数
    Object.keys(params).forEach(key => {
      if (!params[key]) delete params[key];
    });

    const response = await http.get("/system/banList", {params});
    console.log(response);
    if (response.code === 200) {
      banUserList.value = response.data.records;
      pagination.value = {
        ...pagination.value,
        total: response.data.total,
        pages: response.data.pages
      };
    } else {
      ElMessage.error('获取数据失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('网络错误，无法获取封禁列表');
    console.error(error);
  }
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    userId: '',
    userBanType: ''
  };
  pagination.value.currentPage = 1;
  handleSearch();
};

// 打开解封模态框
const handleUnban = () => {
  if (selectedBanIds.value.length === 0) {
    ElMessage.warning('请先选择要解封的记录');
    return;
  }

  unbanForm.value = {
    banIds: [...selectedBanIds.value],
    unbanReason: ''
  };
  unbanDialog.value = true;
};

// 提交解封操作
const confirmUnban = async () => {
  if (!unbanForm.value.unbanReason) {
    ElMessage.warning('请输入解封原因');
    return;
  }

  try {
    const response = await http.put("/system/unbanUsers", unbanForm.value);
    if (response.code === 200) {
      ElMessage.success('解封成功');
      unbanDialog.value = false;
      handleSearch(); // 刷新列表
      selectedBanIds.value = []; // 清空选中
    } else {
      ElMessage.error('解封失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('网络错误，解封失败');
    console.error(error);
  }
};

// 查看封禁详情：将createTime改为banTime
const handleViewDetail = (row) => {
  ElMessageBox.alert(`
    <div style="line-height: 1.8;">
      <p><strong>封禁记录ID：</strong>${row.ubanId}</p>
      <p><strong>用户ID：</strong>${row.userId}</p>
      <p><strong>封禁类型：</strong>${getBanTypeText(row.userBanType)}</p>
      <p><strong>封禁原因：</strong>${row.userReason}</p>
      <p><strong>封禁时间：</strong>${row.banTime ? new Date(row.banTime).toLocaleString() : '未知'}</p>
    </div>
  `, '封禁详情', {
    dangerouslyUseHTMLString: true,
    customClass: 'detail-message-box'
  });
};

// 获取封禁类型文本
const getBanTypeText = (type) => {
  const typeMap = {
    'temporary': '临时封禁',
    'permanent': '永久封禁'
  };
  return typeMap[type] || type;
};

// 分页大小变更
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1;
  handleSearch();
};

// 当前页变更
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  handleSearch();
};

watch(
    () => route.fullPath,
    () => {
      handleSearch();
    }
);

// 组件初始化时加载数据
onMounted(() => {
  handleSearch();
});
</script>

<template>
  <div class="ban-user-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户ID">
          <el-input
              v-model="searchForm.userId"
              clearable
              placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="封禁类型" prop="userBanType">
          <el-select
              v-model="searchForm.userBanType"
              clearable
              placeholder="请选择封禁类型"
              :popper-append-to-body="false"
              style="width: 180px"
          >
            <el-option label="临时封禁" value="temporary"/>
            <el-option label="永久封禁" value="permanent"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--    &lt;!&ndash; 操作按钮区域 &ndash;&gt;-->
    <!--    <div class="operation-buttons">-->
    <!--      <el-button type="success" @click="handleUnban">解封</el-button>-->
    <!--    </div>-->

    <!-- 封禁用户列表表格：将createTime列改为banTime -->
    <el-table
        :data="banUserList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="封禁记录ID" prop="ubanId" width="120"/>
      <el-table-column label="用户ID" prop="userId" width="120"/>
      <el-table-column label="封禁类型" prop="userBanType" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.userBanType === 'temporary' ? 'warning' : 'danger'">
            {{ getBanTypeText(scope.row.userBanType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="封禁原因" min-width="200" prop="userReason">
        <template #default="scope">
          <div class="reason-cell">
            {{ scope.row.userReason }}
          </div>
        </template>
      </el-table-column>
      <!-- 封禁时间列：展示banTime并格式化 -->
      <el-table-column label="封禁时间" prop="banTime" width="180">
        <template #default="scope">
          {{ scope.row.banTime ? new Date(scope.row.banTime).toLocaleString() : '未知' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :pager-count="5"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        next-text="下一页"
        prev-text="上一页"
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 解封用户模态框 -->
    <!--    <el-dialog-->
    <!--        v-model="unbanDialog"-->
    <!--        title="解封用户"-->
    <!--        width="500px"-->
    <!--    >-->
    <!--      <el-form :model="unbanForm" label-width="100px">-->
    <!--        <el-form-item label="选中的记录">-->
    <!--          <div style="display: flex; flex-wrap: wrap; gap: 5px;">-->
    <!--            <el-tag-->
    <!--                v-for="banId in unbanForm.banIds"-->
    <!--                :key="banId"-->
    <!--                type="info"-->
    <!--            >-->
    <!--              记录ID: {{ banId }}-->
    <!--            </el-tag>-->
    <!--          </div>-->
    <!--          <div style="margin-top: 8px; color: #666; font-size: 12px;">-->
    <!--            共 {{ unbanForm.banIds.length }} 条封禁记录-->
    <!--          </div>-->
    <!--        </el-form-item>-->

    <!--        <el-form-item label="解封原因" required>-->
    <!--          <el-input-->
    <!--              v-model="unbanForm.unbanReason"-->
    <!--              :rows="4"-->
    <!--              placeholder="请输入解封原因"-->
    <!--              type="textarea"-->
    <!--          />-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->

    <!--      <template #footer>-->
    <!--        <el-button @click="unbanDialog = false">取消</el-button>-->
    <!--        <el-button type="success" @click="confirmUnban">确认解封</el-button>-->
    <!--      </template>-->
    <!--    </el-dialog>-->
  </div>
</template>

<style scoped>
/* 样式保持不变 */
.ban-user-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 150px);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.operation-buttons .el-button {
  margin-right: 10px;
}

.reason-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.reason-cell:hover {
  white-space: normal;
  word-break: break-all;
}

:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.detail-message-box) {
  min-width: 400px;
}
</style>